#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
生产管理组件
"""

from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
    QScrollArea, QFrame, QMessageBox, QDialog, QDialogButtonBox,
    QCheckBox, QListWidget, QListWidgetItem
)
from PyQt6.QtCore import Qt, pyqtSignal
from PyQt6.QtGui import QFont
from typing import Dict, List, Any, Optional


class ProductionManagementWidget(QWidget):
    """生产管理组件"""
    
    status_update_requested = pyqtSignal(str, str, str)  # pdf_name, serial_number, new_status
    
    def __init__(self, parent: Optional[QWidget] = None):
        super().__init__(parent)
        self.setObjectName("production_management_page")
        
        self.projects: Dict[str, Dict[str, Any]] = {}
        self.project_cards: Dict[str, QWidget] = {}  # 保存项目卡片引用
        
        self._init_ui()
    
    def _init_ui(self):
        """初始化UI"""
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)
        
        # 标题
        title = QLabel("生产管理")
        title.setFont(QFont("Microsoft YaHei", 16, QFont.Weight.Bold))
        main_layout.addWidget(title)
        
        # 滚动区域
        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        
        scroll_content = QWidget()
        scroll_layout = QVBoxLayout(scroll_content)
        scroll_layout.setContentsMargins(0, 0, 0, 0)
        scroll_layout.setSpacing(10)
        
        self.projects_container = QWidget()
        self.projects_layout = QVBoxLayout(self.projects_container)
        self.projects_layout.setContentsMargins(0, 0, 0, 0)
        self.projects_layout.setSpacing(10)
        
        scroll_layout.addWidget(self.projects_container)
        scroll_layout.addStretch()
        
        scroll_area.setWidget(scroll_content)
        main_layout.addWidget(scroll_area)
        
        # 占位提示
        self.placeholder_label = QLabel("暂无项目数据")
        self.placeholder_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.placeholder_label.setStyleSheet("color: #999; font-size: 14px; padding: 40px;")
        self.projects_layout.addWidget(self.placeholder_label)
    
    def update_projects(self, projects_data: List[Dict[str, Any]]):
        """更新项目数据"""
        # 清空现有项目（保留占位符标签）
        placeholder_found = False
        while self.projects_layout.count():
            item = self.projects_layout.takeAt(0)
            widget = item.widget()
            if widget:
                if widget == self.placeholder_label:
                    # 如果是占位符标签，只移除不删除
                    placeholder_found = True
                else:
                    widget.deleteLater()
        
        self.projects = {}
        self.project_cards = {}
        
        if not projects_data:
            # 如果没有数据，显示占位符
            if placeholder_found:
                # 占位符已从布局移除，重新添加
                self.projects_layout.addWidget(self.placeholder_label)
            else:
                # 占位符可能已被删除，重新创建
                try:
                    if self.placeholder_label.parent() is None:
                        self.projects_layout.addWidget(self.placeholder_label)
                    else:
                        # 如果还在布局中，不需要操作
                        pass
                except RuntimeError:
                    # 占位符已被删除，重新创建
                    self.placeholder_label = QLabel("暂无项目数据")
                    self.placeholder_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
                    self.placeholder_label.setStyleSheet("color: #999; font-size: 14px; padding: 40px;")
                    self.projects_layout.addWidget(self.placeholder_label)
            return
        
        # 如果有数据，确保占位符不在布局中
        try:
            if self.placeholder_label.parent() is not None:
                self.placeholder_label.setParent(None)
        except RuntimeError:
            # 占位符已被删除，重新创建（虽然不会显示）
            self.placeholder_label = QLabel("暂无项目数据")
            self.placeholder_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            self.placeholder_label.setStyleSheet("color: #999; font-size: 14px; padding: 40px;")
        
        # 按项目分组
        projects_dict: Dict[str, Dict[str, Any]] = {}
        for item in projects_data:
            pdf_name = item.get("pdf_name", "")
            if not pdf_name:
                continue
            
            if pdf_name not in projects_dict:
                projects_dict[pdf_name] = {
                    "pdf_name": pdf_name,
                    "items": [],
                    "stats": {
                        "not_started": 0,
                        "in_progress": 0,
                        "completed": 0,
                        "qa_failed": 0
                    }
                }
            
            projects_dict[pdf_name]["items"].append(item)
            status = item.get("status", "")
            if status in ["未制作", "未开始", "未处理", "待制作"]:
                projects_dict[pdf_name]["stats"]["not_started"] += 1
            elif status == "制作中":
                projects_dict[pdf_name]["stats"]["in_progress"] += 1
            elif status in ["制作完成", "制作好", "完成", "已完成"]:
                projects_dict[pdf_name]["stats"]["completed"] += 1
            elif "质检" in status:
                projects_dict[pdf_name]["stats"]["qa_failed"] += 1
        
        # 创建项目卡片
        for pdf_name, project_data in sorted(projects_dict.items()):
            card = self._create_project_card(project_data)
            self.projects_layout.addWidget(card)
            self.projects[pdf_name] = project_data
            self.project_cards[pdf_name] = card
    
    def _create_project_card(self, project_data: Dict[str, Any]) -> QWidget:
        """创建项目卡片"""
        card = QFrame()
        card.setObjectName("production_project_card")
        card.setStyleSheet("""
            QFrame#production_project_card {
                background-color: #ffffff;
                border: 1px solid #e0e0e0;
                border-radius: 8px;
                padding: 12px;
            }
        """)
        
        layout = QVBoxLayout(card)
        layout.setContentsMargins(12, 12, 12, 12)
        layout.setSpacing(8)
        
        # 项目名称和状态
        header_layout = QHBoxLayout()
        
        project_name = QLabel(project_data["pdf_name"])
        project_name.setFont(QFont("Microsoft YaHei", 12, QFont.Weight.Bold))
        
        # 根据项目状态显示不同的标签
        stats = project_data["stats"]
        if stats['in_progress'] > 0:
            status_text = "制作中"
            status_color = "#FF9800"
            status_bg = "#fff3e0"
        elif stats['completed'] > 0 and stats['not_started'] == 0 and stats['in_progress'] == 0:
            status_text = "已完成"
            status_color = "#4CAF50"
            status_bg = "#e8f5e9"
        else:
            status_text = "没制作"
            status_color = "#666"
            status_bg = "#e0e0e0"
        
        status_label = QLabel(status_text)
        status_label.setStyleSheet(f"""
            QLabel {{
                background-color: {status_bg};
                color: {status_color};
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 11px;
            }}
        """)
        
        header_layout.addWidget(project_name)
        header_layout.addStretch()
        header_layout.addWidget(status_label)
        
        layout.addLayout(header_layout)
        
        # 状态按钮
        buttons_layout = QHBoxLayout()
        buttons_layout.setSpacing(8)
        
        stats = project_data["stats"]
        pdf_name = project_data["pdf_name"]
        
        # 根据状态显示不同的按钮
        if stats['not_started'] > 0:
            # 有未开始的，显示"开始制作"按钮
            start_btn = QPushButton(f"开始制作 ({stats['not_started']})")
            start_btn.setObjectName("production_start_btn")
            start_btn.setStyleSheet("""
                QPushButton#production_start_btn {
                    background-color: #2196F3;
                    color: white;
                    border: none;
                    border-radius: 4px;
                    padding: 8px 16px;
                    font-weight: bold;
                }
                QPushButton#production_start_btn:hover {
                    background-color: #1976D2;
                }
                QPushButton#production_start_btn:pressed {
                    background-color: #1565C0;
                }
            """)
            start_btn.clicked.connect(lambda checked, pdf=pdf_name: self._on_start_production(pdf))
            buttons_layout.addWidget(start_btn)
            # 保存按钮引用到卡片属性中
            card.start_btn = start_btn
        elif stats['in_progress'] > 0:
            # 有制作中的，显示"制作中"按钮（禁用状态）
            in_progress_btn = QPushButton(f"制作中 ({stats['in_progress']})")
            in_progress_btn.setObjectName("production_in_progress_btn")
            in_progress_btn.setEnabled(False)
            in_progress_btn.setStyleSheet("""
                QPushButton#production_in_progress_btn {
                    background-color: #FF9800;
                    color: white;
                    border: none;
                    border-radius: 4px;
                    padding: 8px 16px;
                    font-weight: bold;
                }
            """)
            buttons_layout.addWidget(in_progress_btn)
            card.start_btn = None
        
        # 制作完成按钮
        complete_btn = QPushButton(f"制作完成 ({stats['completed']})")
        complete_btn.setObjectName("production_complete_btn")
        # 如果有制作中的，则可用；否则禁用
        complete_btn.setEnabled(stats['in_progress'] > 0)
        complete_btn.setStyleSheet("""
            QPushButton#production_complete_btn {
                background-color: #4CAF50;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-weight: bold;
            }
            QPushButton#production_complete_btn:hover {
                background-color: #45a049;
            }
            QPushButton#production_complete_btn:disabled {
                background-color: #cccccc;
                color: #888888;
            }
        """)
        if stats['in_progress'] > 0:
            complete_btn.clicked.connect(lambda checked, pdf=pdf_name: self._on_complete_production(pdf))
        buttons_layout.addWidget(complete_btn)
        card.complete_btn = complete_btn
        
        # 质检报工按钮
        qa_btn = QPushButton(f"质检报工 ({stats['qa_failed']})")
        qa_btn.setObjectName("production_qa_btn")
        # 如果有制作完成或制作中的，则可用；否则禁用
        qa_btn.setEnabled(stats['completed'] > 0 or stats['in_progress'] > 0)
        qa_btn.setStyleSheet("""
            QPushButton#production_qa_btn {
                background-color: #f44336;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 16px;
                font-weight: bold;
            }
            QPushButton#production_qa_btn:hover {
                background-color: #da190b;
            }
            QPushButton#production_qa_btn:disabled {
                background-color: #cccccc;
                color: #888888;
            }
        """)
        if stats['completed'] > 0 or stats['in_progress'] > 0:
            qa_btn.clicked.connect(lambda checked, pdf=pdf_name: self._on_qa_report(pdf))
        buttons_layout.addWidget(qa_btn)
        card.qa_btn = qa_btn
        
        buttons_layout.addStretch()
        
        layout.addLayout(buttons_layout)
        
        return card
    
    def _on_start_production(self, pdf_name: str):
        """开始制作按钮点击"""
        project = self.projects.get(pdf_name)
        if not project:
            return
        
        not_started_count = project["stats"]["not_started"]
        if not_started_count == 0:
            QMessageBox.information(self, "提示", f"{pdf_name} 没有未开始的图案")
            return
        
        # 显示确认对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("开始制作确认")
        dialog.setModal(True)
        
        layout = QVBoxLayout(dialog)
        
        message = QLabel(f"确定要将 {pdf_name} 的所有未开始图案标记为\"制作中\"吗?")
        message.setWordWrap(True)
        layout.addWidget(message)
        
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        layout.addWidget(buttons)
        
        if dialog.exec() == QDialog.DialogCode.Accepted:
            # 检查WebSocket连接状态（优先检查主窗口显示的状态，更可靠）
            main_window = self._get_main_window()
            ws_connected = False
            if main_window:
                # 方法1: 检查主窗口存储的任务服务器状态
                if hasattr(main_window, '_task_server_status'):
                    ws_connected = main_window._task_server_status == "已连接"
                
                # 方法2: 如果方法1不可用，检查任务统计组件的实际连接状态
                if not ws_connected and hasattr(main_window, 'task_statistics_widget'):
                    task_widget = main_window.task_statistics_widget
                    if hasattr(task_widget, '_ws_connected'):
                        ws_connected = task_widget._ws_connected
            
            if not ws_connected:
                reply = QMessageBox.warning(
                    self,
                    "WebSocket未连接",
                    f"任务统计服务未连接，无法发送状态更新。\n\n是否仍要继续？\n（更新请求将失败）",
                    QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
                    QMessageBox.StandardButton.No
                )
                if reply == QMessageBox.StandardButton.No:
                    return
            
            # 获取该项目下所有未开始的图案
            items = project["items"]
            updated_count = 0
            failed_count = 0
            for item in items:
                status = item.get("status", "")
                if status in ["未制作", "未开始", "未处理", "待制作"]:
                    serial_number = item.get("serial_number", "")
                    if serial_number:
                        # 发送状态更新信号
                        try:
                            self.status_update_requested.emit(pdf_name, serial_number, "制作中")
                            updated_count += 1
                        except Exception as e:
                            print(f"❌ 发送状态更新失败: {serial_number} -> {e}")
                            failed_count += 1
            
            if updated_count > 0:
                print(f"开始制作: {pdf_name}, 已发送 {updated_count} 个图案状态更新请求")
                if failed_count > 0:
                    QMessageBox.warning(
                        self, 
                        "部分失败", 
                        f"{pdf_name} 开始制作：\n成功发送 {updated_count} 个更新请求\n失败 {failed_count} 个"
                    )
                elif not ws_connected:
                    QMessageBox.warning(
                        self,
                        "WebSocket未连接",
                        f"{pdf_name} 开始制作：\n已发送 {updated_count} 个更新请求\n但WebSocket未连接，请求可能失败\n请检查任务统计服务连接状态"
                    )
                # 注意：实际的状态更新会通过WebSocket完成，UI会在数据同步后自动刷新
            else:
                if failed_count > 0:
                    QMessageBox.critical(
                        self, 
                        "发送失败", 
                        f"{pdf_name} 开始制作失败：\n所有 {failed_count} 个更新请求都发送失败\n请检查WebSocket连接状态"
                    )
                else:
                    QMessageBox.warning(self, "提示", f"{pdf_name} 没有找到未开始的图案")
    
    def _get_main_window(self):
        """获取主窗口引用"""
        parent = self.parent()
        while parent:
            if hasattr(parent, 'task_statistics_widget'):
                return parent
            parent = parent.parent()
        return None
    
    def _on_complete_production(self, pdf_name: str):
        """制作完成按钮点击"""
        project = self.projects.get(pdf_name)
        if not project:
            return
        
        in_progress_count = project["stats"]["in_progress"]
        if in_progress_count == 0:
            QMessageBox.information(self, "提示", f"{pdf_name} 没有制作中的图案")
            return
        
        # 显示确认对话框
        dialog = QDialog(self)
        dialog.setWindowTitle("制作完成确认")
        dialog.setModal(True)
        
        layout = QVBoxLayout(dialog)
        
        message = QLabel(f"确定要将 {pdf_name} 的所有制作中图案标记为\"制作完成\"吗?")
        message.setWordWrap(True)
        layout.addWidget(message)
        
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        layout.addWidget(buttons)
        
        if dialog.exec() == QDialog.DialogCode.Accepted:
            # 获取该项目下所有制作中的图案
            items = project["items"]
            updated_count = 0
            for item in items:
                status = item.get("status", "")
                if status == "制作中":
                    serial_number = item.get("serial_number", "")
                    if serial_number:
                        # 发送状态更新信号
                        self.status_update_requested.emit(pdf_name, serial_number, "制作完成")
                        updated_count += 1
            
            if updated_count > 0:
                print(f"制作完成: {pdf_name}, 已更新 {updated_count} 个图案状态为制作完成")
                # 注意：实际的状态更新会通过WebSocket完成，UI会在数据同步后自动刷新
            else:
                QMessageBox.warning(self, "提示", f"{pdf_name} 没有找到制作中的图案")
    
    def _on_qa_report(self, pdf_name: str):
        """质检报工处理"""
        project = self.projects.get(pdf_name)
        if not project:
            return
        
        # 获取所有制作完成或制作中的项
        items = project["items"]
        qa_items = [
            item for item in items 
            if item.get("status", "") in ["制作完成", "已完成", "制作中"]
        ]
        
        if not qa_items:
            QMessageBox.warning(self, "提示", f"{pdf_name} 没有找到可质检的图案")
            return
        
        # 创建选择对话框
        dialog = QAReportDialog(qa_items, pdf_name, self)
        if dialog.exec() == QDialog.DialogCode.Accepted:
            selected_items = dialog.get_selected_items()
            if selected_items:
                updated_count = 0
                for item in selected_items:
                    serial_number = item.get("serial_number", "")
                    if serial_number:
                        # 发送状态更新信号，标记为质检不合格
                        self.status_update_requested.emit(pdf_name, serial_number, "质检不合格")
                        updated_count += 1
                
                if updated_count > 0:
                    print(f"质检报工: {pdf_name}, 已标记 {updated_count} 个图案为质检不合格")
                    # 注意：实际的状态更新会通过WebSocket完成，UI会在数据同步后自动刷新
                else:
                    QMessageBox.warning(self, "提示", "没有选择任何图案")


class QAReportDialog(QDialog):
    """质检报工选择对话框"""
    
    def __init__(self, items: List[Dict[str, Any]], pdf_name: str, parent: Optional[QWidget] = None):
        super().__init__(parent)
        self.setWindowTitle(f"质检报工 - {pdf_name}")
        self.setModal(True)
        self.setMinimumSize(500, 400)
        
        self.items = items
        self.selected_items: List[Dict[str, Any]] = []
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(15, 15, 15, 15)
        layout.setSpacing(10)
        
        # 提示信息
        info_label = QLabel("请选择要标记为不合格的图案：")
        info_label.setStyleSheet("font-weight: bold; font-size: 13px;")
        layout.addWidget(info_label)
        
        # 全选/取消全选按钮
        select_buttons_layout = QHBoxLayout()
        select_all_btn = QPushButton("全选")
        select_all_btn.clicked.connect(self._select_all)
        deselect_all_btn = QPushButton("取消全选")
        deselect_all_btn.clicked.connect(self._deselect_all)
        select_buttons_layout.addWidget(select_all_btn)
        select_buttons_layout.addWidget(deselect_all_btn)
        select_buttons_layout.addStretch()
        layout.addLayout(select_buttons_layout)
        
        # 列表显示所有项
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QListWidget.SelectionMode.NoSelection)
        for item in items:
            serial_number = item.get("serial_number", "")
            status = item.get("status", "")
            identifier = item.get("identifier", "")
            
            # 创建列表项
            list_item = QListWidgetItem()
            checkbox = QCheckBox()
            checkbox.setText(f"[{serial_number}] {identifier} - {status}")
            checkbox.setChecked(False)
            checkbox.item_data = item  # 保存原始数据
            
            self.list_widget.addItem(list_item)
            self.list_widget.setItemWidget(list_item, checkbox)
        
        layout.addWidget(self.list_widget)
        
        # 按钮
        buttons = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
        )
        buttons.accepted.connect(self._on_accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)
    
    def _select_all(self):
        """全选"""
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            checkbox = self.list_widget.itemWidget(item)
            if checkbox:
                checkbox.setChecked(True)
    
    def _deselect_all(self):
        """取消全选"""
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            checkbox = self.list_widget.itemWidget(item)
            if checkbox:
                checkbox.setChecked(False)
    
    def _on_accept(self):
        """确认选择"""
        self.selected_items = []
        for i in range(self.list_widget.count()):
            item = self.list_widget.item(i)
            checkbox = self.list_widget.itemWidget(item)
            if checkbox and checkbox.isChecked():
                self.selected_items.append(checkbox.item_data)
        
        if not self.selected_items:
            QMessageBox.warning(self, "提示", "请至少选择一个图案")
            return
        
        self.accept()
    
    def get_selected_items(self) -> List[Dict[str, Any]]:
        """获取选中的项"""
        return self.selected_items

